package indi.mozping;

import lombok.Data;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.io.*;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author by mozping
 * @Classname Test
 * @Description TODO
 * @Date 2019/4/16 20:10
 */
public class Test {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    static List<Entity> list = new ArrayList<>();

    //create_time"":1610018354132  order_id
    public static void main(String[] args) throws ParseException {
        File inFile = new File(".//lag2.csv");
        String inString = "";
        int count = 0;
        TreeMap<String, Long> timeSet = new TreeMap<String, Long>();
        List<Long> timeList = new ArrayList<>();

        try {
            BufferedReader reader = new BufferedReader(new FileReader(inFile));

            while ((inString = reader.readLine()) != null) {
                if (inString.contains("CollectDriverOrderEventConsumer")) {
                    continue;
                }
//                System.out.println(inString + "\n\n");

                String orderId = getOrderId(inString);
                //System.out.print((count + 1) + ": 订单Id：" + orderId + ", ");

                //获取订单createTime
                long msgCreateTime = getMsgCreateTime(inString);
                //System.out.print("订单createTime时间戳：" + msgCreateTime + ", ");
                //System.out.print("订单createTime日期：" + timeStamp2DateStr(msgCreateTime) + ", ");


                //获取生产时间戳
                long producerTimeStamp = getProducerTimeStamp(inString);
                // System.out.print("生产时间戳：" + producerTimeStamp + ", ");
                //System.out.print("生产日期：" + timeStamp2DateStr(producerTimeStamp) + ", ");

                //消费时间戳
                long consumerTimeStamp = getConsumerTimeStamp(inString);

                //System.out.print("消费时间戳：" + consumerTimeStamp + ", ");
                //System.out.print("消费日期：" + timeStamp2DateStr(consumerTimeStamp) + ", ");
                //System.out.print("消费时间-生产时间差：" + (consumerTimeStamp - producerTimeStamp) + " ms" + ", ");
                //System.out.print("消费时间-createTime时间差：" + (consumerTimeStamp - msgCreateTime) + " ms");

                timeSet.put(orderId, (consumerTimeStamp - producerTimeStamp));
                timeList.add((consumerTimeStamp - producerTimeStamp));
                Entity entity = new Entity();
                entity.setOrderId(orderId);
                entity.setOrderCreateTime(msgCreateTime);
                entity.setProducerTime(producerTimeStamp);
                entity.setConsumeTime(consumerTimeStamp);
                entity.setProducerDiff((consumerTimeStamp - producerTimeStamp));
                entity.setCreateTimeDiff((consumerTimeStamp - msgCreateTime));
                list.add(entity);
                count++;
//                if (count == 1) {
//                    break;
//                }
//                System.out.println();
            }
            reader.close();

            list.sort(Comparator.comparingLong(Entity::getProducerTime));
            for (Entity entity : list) {
                System.out.println(entity);
            }
            System.out.println("\n\n---------------------------------------");
            System.out.println("记录条数：" + list.size());
            System.out.println("---------------------------------------");
            //最大时间差
            System.out.println("【消费时间-生产时间差】 部分统计值：");
            {
                Entity max = list.stream().max(Comparator.comparingLong(Entity::getProducerDiff)).get();
                System.out.println("最大时间差：" + max.producerDiff + "ms , orderId: " + max.orderId);
                System.out.println("平均时间差：" + list.stream().mapToLong(p -> p.producerDiff).average().getAsDouble() + "ms");
                System.out.println("时间差小于10ms 的条数：" + list.stream().filter(p -> p.producerDiff <= 10).collect(Collectors.toList()).size());
                System.out.println("时间差大于10ms小于20ms的条数：" + list.stream().filter(p -> p.producerDiff > 10).filter(p -> p.producerDiff <= 20).collect(Collectors.toList()).size());
                System.out.println("时间差大于20ms小于30ms的条数：" + list.stream().filter(p -> p.producerDiff > 20).filter(p -> p.producerDiff <= 30).collect(Collectors.toList()).size());
                System.out.println("时间差大于30ms小于40ms的条数：" + list.stream().filter(p -> p.producerDiff > 30).filter(p -> p.producerDiff <= 40).collect(Collectors.toList()).size());
                System.out.println("时间差大于40ms 的条数：" + list.stream().filter(p -> p.producerDiff > 40).collect(Collectors.toList()).size());
            }
            System.out.println("\n\n---------------------------------------");
            System.out.println("【消费时间-订单消息createTime时间差】部分统计值：");
            {
                Entity max = list.stream().max(Comparator.comparingLong(Entity::getCreateTimeDiff)).get();
                System.out.println("最大时间差：" + max.createTimeDiff + "ms , orderId: " + max.orderId);
                System.out.println("平均时间差：" + list.stream().mapToLong(p -> p.createTimeDiff).average().getAsDouble() + "ms");
                System.out.println("时间差小于100ms 的条数：" + list.stream().filter(p -> p.createTimeDiff <= 100).collect(Collectors.toList()).size());
                System.out.println("时间差大于100ms小于200ms的条数：" + list.stream().filter(p -> p.createTimeDiff > 100).filter(p -> p.createTimeDiff <= 200).collect(Collectors.toList()).size());
                System.out.println("时间差大于200ms小于300ms的条数：" + list.stream().filter(p -> p.createTimeDiff > 200).filter(p -> p.createTimeDiff <= 300).collect(Collectors.toList()).size());
                System.out.println("时间差大于300ms小于400ms的条数：" + list.stream().filter(p -> p.createTimeDiff > 300).filter(p -> p.createTimeDiff <= 400).collect(Collectors.toList()).size());
                System.out.println("时间差大于400ms小于600ms的条数：" + list.stream().filter(p -> p.createTimeDiff > 400).filter(p -> p.createTimeDiff <= 600).collect(Collectors.toList()).size());
                System.out.println("时间差大于600ms小于800ms的条数：" + list.stream().filter(p -> p.createTimeDiff > 600).filter(p -> p.createTimeDiff <= 800).collect(Collectors.toList()).size());
                System.out.println("时间差大于800ms 的条数：" + list.stream().filter(p -> p.createTimeDiff > 800).collect(Collectors.toList()).size());
            }
        } catch (FileNotFoundException ex) {
            System.out.println("没找到文件！");
        } catch (IOException ex) {
            System.out.println("读写文件出错！");
        }
    }

    private static String getOrderId(String msg) {
        String substring = msg.substring(msg.indexOf("order_id"), msg.indexOf("order_id") + 40);
        String orderId = substring.substring(substring.indexOf(":") + 1, substring.indexOf(","));
        while (orderId.startsWith("\"")) {
            orderId = orderId.substring(1);
        }
        while (orderId.endsWith("\"")) {
            orderId = orderId.substring(0, orderId.length() - 1);
        }
        return orderId;
    }

    static long getMsgCreateTime(String msg) {
        int index = msg.indexOf("RecordHeader");
        String substring = msg.substring(index);
        String create_time = substring.substring(substring.indexOf("create_time") + 14, substring.indexOf("create_time") + 14 + 13);
        return new Long(create_time);
    }

    static long getProducerTimeStamp(String msg) {
        return new Long(msg.substring(msg.indexOf("CreateTime") + 13, msg.indexOf("CreateTime") + 13 + 13));
    }

    static long getConsumerTimeStamp(String msg) throws ParseException {
        String substring = msg.substring(msg.indexOf("###") + 6, msg.indexOf("###") + 6 + 23);
        Date date = sdf.parse(substring);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getTimeInMillis();
    }

    //时间戳转日期String
    static String timeStamp2DateStr(long timeStamp) {
        Date producerDate = new Date(timeStamp);
        return sdf.format(producerDate);
    }

    @Data
    static class Entity {
        private String orderId;
        private long orderCreateTime;
        private long producerTime;
        private long consumeTime;
        private long producerDiff;
        private long createTimeDiff;

        @Override
        public String toString() {
            return "orderId='" + orderId + '\'' +
                    ", 订单createTime日期:" + timeStamp2DateStr(orderCreateTime) +
                    ", 生产日期=" + timeStamp2DateStr(producerTime) +
                    ", 消费日期=" + timeStamp2DateStr(consumeTime) +
                    ", 消费时间-生产时间差=" + producerDiff + " ms" +
                    ", 消费时间-订单消息createTime时间差=" + createTimeDiff + " ms";
        }
    }

    public static void main1(String[] args) {

        Field[] fieldsConsumer = ConsumerConfig.class.getDeclaredFields();
        ArrayList<String> consumerArr = new ArrayList<String>();
        for (int i = 0, len = fieldsConsumer.length; i < len; i++) {
            // 对于每个属性，获取属性名
            String varName = fieldsConsumer[i].getName();
            consumerArr.add(varName);
        }
        System.out.println("消费者配置个数为：" + consumerArr.size());


        Field[] fieldsProducer = ProducerConfig.class.getDeclaredFields();
        ArrayList<String> producerArr = new ArrayList<String>();
        for (int i = 0, len = fieldsProducer.length; i < len; i++) {
            // 对于每个属性，获取属性名
            String varName = fieldsProducer[i].getName();
            producerArr.add(varName);
        }

        System.out.println("生产者配置个数为：" + producerArr.size());
        int common = 0;
        for (String config : producerArr) {
            if (consumerArr.contains(config) &&
                    !config.contains("DOC")) {
                System.out.println(config);

                common++;
            }
        }

        System.out.println("公共个数为：" + common);
    }
}

